import axios from 'axios'
import store from '@/store'

export async function upload(files, signal) {
  const token = store.state.user.token

  if (!token) {
    throw new Error('Token not found')
  }

  // 创建一个数组来保存所有的上传请求
  const uploadPromises = []

  files.forEach(file => {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('type', 'businessLicense')

    // 对每个文件发起一个独立的请求
    uploadPromises.push(
      axios.post('https://api-hmzs.itheima.net/tj/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'Authorization': token
        },
        signal: signal // 传递 signal
      })
    )
  })

  try {
    // 使用 Promise.all 来并发执行所有的上传请求
    const responses = await Promise.all(uploadPromises)
    console.log('All files uploaded successfully:', responses)
    return responses.map(response => response.data)
  } catch (error) {
    console.error('One or more uploads failed:', error)
    // 如果任意一个请求失败，Promise.all 会抛出错误
    throw error
  }
}
